<template>
  <el-dialog title="编辑头像" :close-on-click-modal="false" :visible.sync="visible">
    <basic-container>
      <template>
        <el-row>
          <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="150px" class="demo-ruleForm">
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="头像">
                  <el-upload :headers="headers" :show-file-list="false" :on-success="handleAvatarSuccess"
                    class="avatar-uploader" action="/admin/sys-file/upload">
                    <img v-if="ruleForm.avatar" id="avatar" :src="avatarUrl" class="avatar" />
                    <i v-else class="el-icon-plus avatar-uploader-icon" />
                  </el-upload>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" v-if="canSubmit" @click="submitForm()">提交</el-button>
                   <el-button @click="visible = false">取消</el-button>
                </el-form-item>
              </div>
            </el-col>
          </el-form>
        </el-row>
      </template>
    </basic-container>
  </el-dialog>
</template>

<script>
  import {
    handleImg,
    openWindow
  } from "@/util/util";
  import {
    mapState
  } from "vuex";
  import store from "@/store";


  import {
    updateHead,
    getObj
  } from "@/api/admin/user";

  export default {
      
    data() {
      return {
        canSubmit: false,
        visible: false,
        avatarUrl: "",
        headers: {
          Authorization: "Bearer " + store.getters.access_token,
        },
        ruleForm: {
          id: 0,
          avatar: "",
        },
        rules: {},
      };
    },

    methods: {
      init(id) {
        this.ruleForm.id = id || 0;
        this.visible = true;
        this.canSubmit = true;
        this.$nextTick(() => {
          this.$refs['ruleForm'].resetFields()
          if (this.ruleForm.id) {
            getObj(this.ruleForm.id).then(response => {
              this.ruleForm.avatar = response.data.data.avatar;
              this.ruleForm.userId = response.data.data.userId;
              this.avatarUrl=response.data.data.avatar;
            })
          }
        })
      },
      submitForm() {
        this.$refs.ruleForm.validate((valid) => {
          if (!valid) {
            return false;
          }
          this.canSubmit = false;
          updateHead(this.ruleForm).then((response) => {
            this.$notify.success("修改成功");
             this.visible = false
          }).catch(() => {
            this.canSubmit = true;
          });
        });
      },
      handleAvatarSuccess(res, file) {
        this.avatarUrl = URL.createObjectURL(file.raw);
        this.ruleForm.avatar = res.data.url;
      },

    },
  };

</script>
<style lang="scss">
  @import "@/styles/info.scss";

</style>
